package com.pac.weixin.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.common.util.LogicException;
import com.common.util.MsgKeyContent;
import com.common.util.SessionKeyContent;
import com.pac.user.bean.UserBean;
import com.pac.weixin.bean.WxChatBean;
import com.pac.weixin.service.WxChatService;

/**
 * 微信聊天controller
 * 
 * @author lujun.chen
 * @version [版本号, 2015年2月27日]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@Controller
@Scope("prototype")
@RequestMapping("/weixin/chat")
public class WxChatController {

	private static Logger logger = Logger.getLogger(WxChatController.class);

	@Autowired
	private WxChatService wxChatService;

	/**
	 * 医生获取聊天记录
	 * 
	 * @param request
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/doctor/chatlist")
	@ResponseBody
	public List<WxChatBean> queryDoctorChat(HttpServletRequest request) {
		// 从session中获取用户ID
		HttpSession session = request.getSession();
		UserBean userBeans = (UserBean) session
				.getAttribute(SessionKeyContent.SESSION_KEY_OBJ_USER_BEAN);

		if (null == userBeans) {
			return null;
		}

		WxChatBean wxChatBean = new WxChatBean();
		wxChatBean.setUserId(userBeans.getId());

		return wxChatService.pacQueryWxChat(wxChatBean);
	}

	/**
	 * 医生向微信发送消息
	 * 
	 * @param request
	 * @param wxChatBean
	 * @return
	 * @see [类、类#方法、类#成员]
	 */
	@RequestMapping("/doctor/chatadd")
	@ResponseBody
	public Map<String, Object> addDoctorChat(HttpServletRequest request,
			WxChatBean wxChatBean) {

		boolean result = true;
		String msg = "";

		try {
			
			// 从session中获取用户ID
			HttpSession session = request.getSession();
			UserBean userBeans = (UserBean) session
					.getAttribute(SessionKeyContent.SESSION_KEY_OBJ_USER_BEAN);
			
			wxChatBean.setUserId(userBeans.getId());
			
			wxChatService.addChatFromPac(wxChatBean);
			result = true;
			msg = "添加成功";
		} catch (LogicException ex) {
			result = false;
			msg = ex.getMessage();
		} catch (Exception ex) {
			logger.error("保存向微信发送的数据出错，" + ex);
			result = false;
			msg = "系统错误，请稍后再试";
		}

		Map<String, Object> map = new HashMap<String, Object>();
		map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT, result);
		map.put(MsgKeyContent.PAGE_AJAX_OPERATION_RESULT_MSG, msg);

		return map;
	}
	
}
